package com.hue.controller;


import com.hue.entity.User;
import com.hue.service.UserService;
import com.hue.utils.MD5Utils;
import com.hue.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 姚凤桥
 * @since 2021-07-15
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
        压力测试:
            QPS:1100
     */
    @GetMapping("/info")
    @ResponseBody
    public User info(@CookieValue("token") String token){
        User user = redisUtils.getUser(token);
        return user;
    }

    /*
        生成5000个用户
     */
    @GetMapping("/add")
    @ResponseBody
    public String add(){
        User user = null;
        for (int i = 0; i < 5000; i++) {
            user = new User();
            user.setMobile(getPhone());
            user.setNickname("abc");
            user.setPassword(MD5Utils.MD5Encoding("123456"));
            user.setSalt("1a2b3c4d");
            userService.save(user);
        }
        return "生成完毕";
    }

    /*
        将5000个用户全部登录，产生token存储到文件里
     */
    @GetMapping("/login")
    @ResponseBody
    public String login() throws IOException {
        File file = new File("F://login.txt");
        FileWriter fw = new FileWriter(file);
        List<User> users = userService.list(null);
        for(User user:users){
            String token = UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set("user:"+token,user,30, TimeUnit.MINUTES);
            fw.write(token+"\n");
        }
        fw.close();
        return "登录完成!";
    }

    //随机生成11位手机号
    public String getPhone(){
        String phone = "1";
        for (int i = 0; i < 10; i++) {
            phone += (int)(Math.random()*10);
        }
        return phone;
    }
}

